%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 17.03.2009
%% Description: TODO: Describe.
%%--------------------------------------------------------------------
-module(iter_pushback).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/1,
		 open/1,
		 next/1,
		 close/1,
		 pushback/2,
		 test/0
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------

new(BaseIter) 
	when is_record(BaseIter, iter)->
	iter:from_module(
		?MODULE, 
		{BaseIter, []}).

open({Iter,[]}) ->
	State=iter:open(Iter),
	{pb,State,[]}.

next({pb,State,[H|T]}) ->
	{{pb,State,T},H};
next({pb,State,[]}) ->
	{State1,Item}=iter:next(State),
	{{pb,State1,[]},Item}.
pushback({ISpec,{pb,State,Buff}},Item) ->
	{ISpec,{pb,State,[Item|Buff]}}.

close({pb,State,_}) ->
	ok=iter:close(State).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test() ->
	I=new(iter:from_list([1,2,3,4,5])),
	iter:print(I),
	S=iter:open(I),
	{S1,1}=iter:next(S),
	{S2,2}=iter:next(S1),
	{S3,3}=iter:next(S2),
	{S4,4}=iter:next(S3),
	S5=iter_pushback:pushback(S4,4),
	{S6,4}=iter:next(S5),
	{_S7,5}=iter:next(S6).

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------